package top.healthylife.utils;/*
 *@Author GaoZeXi
 *@Created time 2020/4/9 21:49
 *@Description:
 * Step by Step  and Stand on,  You Are The Best Investment!!!
 */

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiniuyunUtils {

    public static  final String ACCESSKEY="ytt7jrOp-_piaBHJ4ucovfnRgIyE-mVFdqHSGWEb";
    public static  final String SECRETKEY="HQfy6Q9tii8myrFOPBgXJIEUqfE1Ail6FJ1DRp-H";
    public static final String BUCKET="healthylife-top";

    public static void upload2Qiniu(byte[] bytes,String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        //认证
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        String upToken = auth.uploadToken(BUCKET);
        try {
            Response res = uploadManager.put(bytes, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException e) {
            Response res = e.response;
            try {
                System.err.println(res.bodyString());
            } catch (QiniuException e1) {
                e1.printStackTrace();
                //ignore
            }
        }
    }

    //删除文件

    public static void deleteFileFromQiniu(String fileName){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        String key = fileName;
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(BUCKET,key);
        } catch (QiniuException e) {
            System.err.println(e.code());
            System.err.println(e.response.toString());
        }
    }


}
